package com.fuyd.pms.background.web.account;

import com.fuyd.pms.entity.account.MerchantUser;
import com.fuyd.pms.background.web.base.BaseController;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 用户名密码登录，LoginController负责打开登录页面(GET请求)和登录出错页面(POST请求)，
 * <p/>
 * 真正登录的POST请求由Filter完成,
 */
@Controller
@RequestMapping(value = "/login")
public class LoginController extends BaseController {

    /**
     * 登录页面
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public String login() {
        MerchantUser merchantUser = getCurrentUser();
        if (merchantUser != null) {
            //若shiro中存在用户，则直接跳转至商品添加的页面
            return "redirect:/merchandise";
        }
        return "account/login";
    }

    /**
     * 登陆失败，该方法中，由FormAuthenticationFilter来调用Shiro相关的安全认证，认证成功，则跳转shiroFilter中配置的successUrl
     *
     * @param username 用户名
     * @param model
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String username, Model model) {
        model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, username);
        return "account/login";
    }
}
